// var validator = require('validator');
var urllib = require('urllib');
var querystring = require('querystring');


var DoubanApi = function () {
    this.api_hostname = 'api.douban.com';
    this.api_root = 'https://' + this.api_hostname + '/';
    this.app_key = '';
    this.app_secret = '';
    this.redirect_uri = '';
    this.token = null;
    this.access_token = '';
};

module.exports = new DoubanApi();


var pt = DoubanApi.prototype;

pt.init = function (opt) {
    this.app_key = opt.app_key;
    this.app_secret = opt.app_secret;
    this.redirect_uri = opt.app_redirect_uri;
};


pt.request = function (apiURI, options, callback) {
    var self = this;
    var url = self.api_root + apiURI;
    options.headers = { 'Authorization': 'Bearer ' + this.access_token };
    console.log('request', url, options);
    urllib.request(url, options, function (err, data, res) {
        if (typeof callback == 'function') {
            // console.log(res.statusCode);
            // console.log(res.headers);
            if (err) {
                callback(err, null);
            } else {
                callback(err, JSON.parse(data));
            }
        }
    });
};


pt.requestGet = function (apiURI, params, callback) {
    var options = {
        method: 'GET',
        data: params || {}
    };
    this.request(apiURI, options, callback);
};


pt.requestPost = function (apiURI, params, callback) {
    var options = {
        method: 'POST',
        data: params || {}
    };
    this.request(apiURI, options, callback);
};


pt._getOauthrizationURL = function () {
    var params = {
        client_id: this.app_key,
        redirect_uri: this.redirect_uri,
        response_type: 'code'
    };
    var query = querystring.stringify(params);
    return 'https://www.douban.com/service/auth2/auth?' + query;
};


pt.authorize = function (res) {
    var url = this._getOauthrizationURL();
    // console.log('weibo.authorize', url);
    if (res.redirect) {
        res.redirect(url);
    } else {
        res.writeHead(302, {
            'Location': url
            //add other headers here...
        });
        res.end();
    }
};


pt.accessToken = function (code, callback) {
    var self = this;
    var url = 'https://www.douban.com/service/auth2/token';
    var params = {
        method: 'POST',
        data: {
            client_id: self.app_key,
            client_secret: self.app_secret,
            redirect_uri: self.redirect_uri,
            grant_type: 'authorization_code',
            code: code
        }
    };
    urllib.request(url, params, function (err, data, res) {
        // self.token = data;
        // self.access_token = data.access_token;
        // console.log(res.statusCode);
        // console.log(res.headers);
        // data is Buffer instance
        // console.log(data.toString());
        if (typeof callback == 'function') {
            if (err) {
                console.error(err);
            } else {
                callback(err, JSON.parse(data));
            }
        }
    });
};


pt.userGetByUid = function (uid, callback) {
    this.requestGet('v2/user/' + uid, null, callback);
};

pt.userGetByName = function (name, callback) {
    this.requestGet('v2/user/' + name, null, callback);
};

pt.usersFollowers = function (id, callback) {
    var uri = 'shuo/v2/users/:id/followers';
    this.requestGet(uri.replace(/\:id/, id), null, callback);
};

pt.statusesHomeTimeline = function (params, callback) {
    var uri = 'shuo/v2/statuses/home_timeline';
    this.requestGet(uri, params, callback);
};

pt.statusesUserTimeline = function (name, callback) {
    var uri = 'shuo/v2/statuses/user_timeline/:name';
    this.requestGet(uri.replace(/\:name/, name), null, callback);
};

pt.statusesPost = function (params, callback) {
    var uri = 'shuo/v2/statuses/';
    this.requestPost(uri, params, callback);
};
